package l1j.server.server.utils;

import static l1j.server.server.model.skill.L1SkillId.EXP_UP;
import static l1j.server.server.model.skill.L1SkillId.AI_CheckEffect;
import static l1j.server.server.model.skill.L1SkillId.AI_TimeEffect;

import java.util.ArrayList;
import java.util.List;
import java.util.logging.Logger;

import l1j.opqlo.Server.L1World.L1World;
import l1j.server.Config;
import l1j.server.server.datatables.ExpTable;
import l1j.server.server.datatables.MapsTable;
import l1j.server.server.datatables.PetTable;
import l1j.server.server.model.L1Character;
import l1j.server.server.model.L1Object;
import l1j.server.server.model.L1Party;
import l1j.server.server.model.Instance.L1NpcInstance;
import l1j.server.server.model.Instance.L1PcInstance;
import l1j.server.server.model.Instance.L1PetInstance;
import l1j.server.server.model.Instance.L1SummonInstance;
import l1j.server.server.serverpackets.S_ChatPacket;
import l1j.server.server.serverpackets.S_PetPack;
import l1j.server.server.serverpackets.S_ServerMessage;
import l1j.server.server.serverpackets.S_SkillIconExp;
import l1j.server.server.serverpackets.S_SystemMessage;
import l1j.server.server.templates.L1Pet;

public class CalcExp {

	private static Logger _log = Logger.getLogger(CalcExp.class.getName());

	// private static final int MAX_EXP = ExpTable.getExpByLevel(100) - 1;

	// private static L1NpcInstance _npc = null;//TODO 殷海薩的祝福

	public static void AddExp(final L1PcInstance pc, final long acquireExp,final int lawful) {

		final int add_lawful = (int) (lawful * Config.RATE_LA) * -1;
		pc.addLawful(add_lawful);

		// opqlo 掛機檢測次數
		if(Config.AI && MapsTable.getInstance().isAiCheck(pc.getMapId())){
			if(!pc.hasSkillEffect(AI_TimeEffect)){
				if(pc.getAICount()>pc.getCheckCount()){
					pc.addCheckCount();
					if(pc.isGm()){
						pc.sendPackets(new S_SystemMessage("檢測次數： "+pc.getAICount()+" 目前次數： "+pc.getCheckCount())); 
					}
				}else{
					pc.setTeleport(true);
					pc.setCheckCount(0);
					pc.setSkillEffect(AI_CheckEffect, 150); 
					try{
						final L1Party party = pc.getParty();
						if(party !=null){
							final S_ChatPacket packets = new S_ChatPacket(pc, "隊友們，我去檢測囉!",35, 0);
							for(final L1PcInstance tgpc : party.getMembers()){
								tgpc.sendPackets(packets);
							}
						}
					}catch(Exception e){
					}
				}
			}
		}
		// opqlo 掛機檢測次數END
		if (acquireExp <= 0) {
			return;
		}
		final int level = pc.getLevel();
		//		if (level == 99) {
		//			// pc.sendPackets(new S_SystemMessage("已經可以轉生了。"));
		//			return;
		//		}
		// double foodBonus = 1.0;
		/*
		 * if (pc.hasSkillEffect(COOKING_1_7_N) ||
		 * pc.hasSkillEffect(COOKING_1_7_S)) { foodBonus = 1.01; }else if
		 * (pc.hasSkillEffect(COOKING_2_7_N) ||
		 * pc.hasSkillEffect(COOKING_2_7_S)) { foodBonus = 1.02; }else if
		 * (pc.hasSkillEffect(COOKING_3_7_N) ||
		 * pc.hasSkillEffect(COOKING_3_7_S)) { foodBonus = 1.03; }
		 */

		double ainBonus = 1.0;// TODO 殷海薩的祝福
		// TODO 殷海薩的祝福 計算公式仍需驗證
		if (pc.getAinPoint() > 0) {
			// if (!(_npc instanceof L1PetInstance
			// TODO 木人寵物召喚不計算加成
			// || _npc instanceof L1SummonInstance || _npc instanceof
			// L1ScarecrowInstance)) {
			// TODO 木人寵物召喚不計算加成
			pc.setAinPoint(pc.getAinPoint() - 1);
			pc.sendPackets(new S_SkillIconExp(pc.getAinPoint()));
			ainBonus = 1.77;// TODO 額外的經驗 77%
			// }
		}
		// TODO 殷海薩的祝福 計算公式仍需驗證

		final double VipRate = pc.isVIP == true ? 1.5 : 1.0;

		if (!pc.hasSkillEffect(EXP_UP) && pc.getExpRate != 1) {
			pc.getExpRate = 1;
		}
		long add_exp = (long) Math.max(
				acquireExp
				* (Config.RATE_XP
						* MapsTable.getInstance().getExpRate(
								pc.getMapId())
								* ainBonus
								* ExpTable.getLevelBouns(level)
								* ExpTable.getPenaltyRate(level)
								* ExpTable.getLevelMetRate(pc
										.get_metempsychosis()) * VipRate
										* pc.getExpRate * pc.getExpUp())
										* pc.getDollList().getExpAddRate(), 0);

		// TODO 魔法娃娃經驗設定DB化byhot183

		final int rate = ExpTable.getLevelMetRate2(pc.get_metempsychosis());
		if (rate != 0) {
			add_exp = add_exp >> rate;
		}
		add_exp = Math.min(add_exp,ExpTable.getLevelUpNeedExp(pc.getExp(), level));
		final long needexp = Math.max(1, add_exp);
		pc.addExp(needexp);
	}

	private static void AddExpPet(final L1PetInstance pet, final long acquireExp) {
		final L1PcInstance pc = (L1PcInstance) pet.getMaster();

		final int petItemObjId = pet.getItemObjId();

		final int levelBefore = pet.getLevel();
		// TODO 寵物經驗倍率
		final int totalExp = (int) Math.min(acquireExp * Config.RATE_XP_PET
				+ pet.getExp(),
				ExpTable.getExpByLevel(Config.Pet_Max_LV + 1) - 1);
		// TODO 寵物經驗倍率

		/*
		 * //TODO 寵物最高等級 if (totalExp >=
		 * ExpTable.getExpByLevel(Config.Pet_Max_LV + 1)) { totalExp =
		 * ExpTable.getExpByLevel(Config.Pet_Max_LV + 1) - 1; //TODO 寵物最高等級 }
		 */
		pet.setExp(totalExp);

		pet.setLevel(ExpTable.getLevelByExp(totalExp));

		final int expPercentage = ExpTable.getExpPercentage(pet.getLevel(),
				totalExp);

		final int gap = pet.getLevel() - levelBefore;
		for (int i = 1; i <= gap; i++) {
			pet.addMaxHp(pet.getPetType().getHpUpRange().randomValue());
			pet.addMaxMp(pet.getPetType().getMpUpRange().randomValue());
		}

		pet.setExpPercent(expPercentage);
		pc.sendPackets(new S_PetPack(pet, pc));

		if (gap != 0) { // レベルアップしたらDBに書き込む
			final L1Pet petTemplate = PetTable.getInstance().getTemplate(
					petItemObjId);
			if (petTemplate == null) { // PetTableにない
				_log.warning("L1Pet == null");
				return;
			}
			petTemplate.set_exp(pet.getExp());
			petTemplate.set_level(pet.getLevel());
			petTemplate.set_hp(pet.getMaxHp());
			petTemplate.set_mp(pet.getMaxMp());
			PetTable.getInstance().storePet(petTemplate); // DBに書き込み
			pc.sendPackets(new S_ServerMessage(320, pet.getName())); // \f1%0のレベルが上がりました。
		}
	}

	public static void calcExp(final L1PcInstance l1pcinstance,
			final int targetid, final ArrayList<?> acquisitorList,
			final List<Integer> hateList, final long exp) {

		int i = 0;
		double party_level = 0;
		double dist = 0;
		long member_exp = 0;
		int member_lawful = 0;
		final L1Object l1object = L1World.getInstance().findObject(targetid);
		final L1NpcInstance npc = (L1NpcInstance) l1object;

		// ヘイトの合計を取得
		L1Character acquisitor;
		int hate = 0;
		long acquire_exp = 0;
		int acquire_lawful = 0;
		long party_exp = 0;
		int party_lawful = 0;
		long totalHateExp = 0;
		int totalHateLawful = 0;
		long partyHateExp = 0;
		int partyHateLawful = 0;
		long ownHateExp = 0;

		if (acquisitorList.size() != hateList.size()) {
			return;
		}
		for (i = hateList.size() - 1; i >= 0; i--) {
			acquisitor = (L1Character) acquisitorList.get(i);
			hate = hateList.get(i);
			if (acquisitor != null && !acquisitor.isDead()) {
				totalHateExp += hate;
				if (acquisitor instanceof L1PcInstance) {
					totalHateLawful += hate;
				}
			} else { // nullだったり死んでいたら排除
				acquisitorList.remove(i);
				hateList.remove(i);
			}
		}
		if (totalHateExp == 0) { // 取得者がいない場合
			return;
		}

		if (l1object != null && !(npc instanceof L1PetInstance)
				&& !(npc instanceof L1SummonInstance)) {
			// int exp = npc.get_exp();
			if (!L1World.getInstance().isProcessingContributionTotal()
					&& l1pcinstance.getHomeTownId() > 0) {
				final int contribution = npc.getLevel() / 10;
				l1pcinstance.addContribution(contribution);
			}
			final int lawful = npc.getLawful();

			if (l1pcinstance.isInParty()) { // 組隊中
				// パーティーのヘイトの合計を算出
				// パーティーメンバー以外にはそのまま配分
				partyHateExp = 0;
				partyHateLawful = 0;
				for (i = hateList.size() - 1; i >= 0; i--) {
					acquisitor = (L1Character) acquisitorList.get(i);
					hate = hateList.get(i);
					if (acquisitor instanceof L1PcInstance) {
						final L1PcInstance pc = (L1PcInstance) acquisitor;
						if (pc == l1pcinstance) {
							partyHateExp += hate;
							partyHateLawful += hate;
						} else if (l1pcinstance.getParty().isMember(pc)) {
							partyHateExp += hate;
							partyHateLawful += hate;
						} else {
							if (totalHateExp > 0) {
								acquire_exp = exp * hate / totalHateExp;
							}
							if (totalHateLawful > 0) {
								acquire_lawful = lawful * hate
										/ totalHateLawful;
							}
							AddExp(pc, acquire_exp, acquire_lawful);
						}
					} else if (acquisitor instanceof L1PetInstance) {
						final L1PetInstance pet = (L1PetInstance) acquisitor;
						final L1PcInstance master = (L1PcInstance) pet
								.getMaster();
						if (master == l1pcinstance) {
							partyHateExp += hate;
						} else if (l1pcinstance.getParty().isMember(master)) {
							partyHateExp += hate;
						} else {
							if (totalHateExp > 0) {
								acquire_exp = exp * hate / totalHateExp;
							}
							AddExpPet(pet, acquire_exp);
						}
					} else if (acquisitor instanceof L1SummonInstance) {
						final L1SummonInstance summon = (L1SummonInstance) acquisitor;
						final L1PcInstance master = (L1PcInstance) summon
								.getMaster();
						if (master == l1pcinstance) {
							partyHateExp += hate;
						} else if (l1pcinstance.getParty().isMember(master)) {
							partyHateExp += hate;
						} else {
						}
					}
				}
				if (totalHateExp > 0) {
					party_exp = exp * partyHateExp / totalHateExp;
				}
				if (totalHateLawful > 0) {
					party_lawful = lawful * partyHateLawful / totalHateLawful;
				}

				// EXP、ロウフル配分

				// 紅利經驗計算
				double pri_bonus = 0;
				final L1PcInstance leader = l1pcinstance.getParty().getLeader();
				if (leader.isCrown()
						&& (l1pcinstance.knownsObject(leader) || l1pcinstance
								.equals(leader))) {
					pri_bonus = 0.059;
				}

				// PT経験値の計算
				final L1PcInstance[] ptMembers = l1pcinstance.getParty().getMembers();
				double pt_bonus = 0;
				for (final L1PcInstance each : ptMembers) {
					if (l1pcinstance.knownsObject(each) || l1pcinstance.equals(each)) {
						party_level += each.getLevel() * each.getLevel();
					}
					if (l1pcinstance.knownsObject(each)) {
						// pt_bonus += 0.04;
						pt_bonus += 1; // opqlo 組隊經驗增加
					}
				}

				party_exp = (long) (party_exp * (1 + pt_bonus + pri_bonus));

				// 自キャラクターとそのペット・サモンのヘイトの合計を算出
				if (party_level > 0) {
					dist = l1pcinstance.getLevel() * l1pcinstance.getLevel()
							/ party_level;
				}
				member_exp = (long) (party_exp * dist);
				member_lawful = (int) (party_lawful * dist);

				ownHateExp = 0;
				for (i = hateList.size() - 1; i >= 0; i--) {
					acquisitor = (L1Character) acquisitorList.get(i);
					hate = hateList.get(i);
					if (acquisitor instanceof L1PcInstance) {
						final L1PcInstance pc = (L1PcInstance) acquisitor;
						if (pc == l1pcinstance) {
							ownHateExp += hate;
						}
					} else if (acquisitor instanceof L1PetInstance) {
						final L1PetInstance pet = (L1PetInstance) acquisitor;
						final L1PcInstance master = (L1PcInstance) pet
								.getMaster();
						if (master == l1pcinstance) {
							ownHateExp += hate;
						}
					} else if (acquisitor instanceof L1SummonInstance) {
						final L1SummonInstance summon = (L1SummonInstance) acquisitor;
						final L1PcInstance master = (L1PcInstance) summon
								.getMaster();
						if (master == l1pcinstance) {
							ownHateExp += hate;
						}
					}
				}
				// 自キャラクターとそのペット・サモンに分配
				if (ownHateExp != 0) { // 攻撃に参加していた
					for (i = hateList.size() - 1; i >= 0; i--) {
						acquisitor = (L1Character) acquisitorList.get(i);
						hate = hateList.get(i);
						if (acquisitor instanceof L1PcInstance) {
							final L1PcInstance pc = (L1PcInstance) acquisitor;
							if (pc == l1pcinstance) {
								if (ownHateExp > 0) {
									acquire_exp = member_exp * hate
											/ ownHateExp;
								}
								AddExp(pc, acquire_exp, member_lawful);
							}
						} else if (acquisitor instanceof L1PetInstance) {
							final L1PetInstance pet = (L1PetInstance) acquisitor;
							final L1PcInstance master = (L1PcInstance) pet
									.getMaster();
							if (master == l1pcinstance) {
								if (ownHateExp > 0) {
									acquire_exp = member_exp * hate
											/ ownHateExp;
								}
								AddExpPet(pet, acquire_exp);
							}
						} else if (acquisitor instanceof L1SummonInstance) {
						}
					}
				} else { // 攻撃に参加していなかった
					// 自キャラクターのみに分配
					AddExp(l1pcinstance, member_exp, member_lawful);
				}

				// パーティーメンバーとそのペット・サモンのヘイトの合計を算出
				for (final L1PcInstance ptMember : ptMembers) {
					if (l1pcinstance.knownsObject(ptMember)) {
						if (party_level > 0) {
							dist = ptMember.getLevel() * ptMember.getLevel()
									/ party_level;
						}
						member_exp = (long) (party_exp * dist);
						member_lawful = (int) (party_lawful * dist);

						ownHateExp = 0;
						for (i = hateList.size() - 1; i >= 0; i--) {
							acquisitor = (L1Character) acquisitorList.get(i);
							hate = hateList.get(i);
							if (acquisitor instanceof L1PcInstance) {
								final L1PcInstance pc = (L1PcInstance) acquisitor;
								if (pc == ptMember) {
									ownHateExp += hate;
								}
							} else if (acquisitor instanceof L1PetInstance) {
								final L1PetInstance pet = (L1PetInstance) acquisitor;
								final L1PcInstance master = (L1PcInstance) pet
										.getMaster();
								if (master == ptMember) {
									ownHateExp += hate;
								}
							} else if (acquisitor instanceof L1SummonInstance) {
								final L1SummonInstance summon = (L1SummonInstance) acquisitor;
								final L1PcInstance master = (L1PcInstance) summon
										.getMaster();
								if (master == ptMember) {
									ownHateExp += hate;
								}
							}
						}
						// パーティーメンバーとそのペット・サモンに分配
						if (ownHateExp != 0) { // 攻撃に参加していた
							for (i = hateList.size() - 1; i >= 0; i--) {
								acquisitor = (L1Character) acquisitorList
										.get(i);
								hate = hateList.get(i);
								if (acquisitor instanceof L1PcInstance) {
									final L1PcInstance pc = (L1PcInstance) acquisitor;
									if (pc == ptMember) {
										if (ownHateExp > 0) {
											acquire_exp = member_exp * hate
													/ ownHateExp;
										}
										AddExp(pc, acquire_exp, member_lawful);
									}
								} else if (acquisitor instanceof L1PetInstance) {
									final L1PetInstance pet = (L1PetInstance) acquisitor;
									final L1PcInstance master = (L1PcInstance) pet
											.getMaster();
									if (master == ptMember) {
										if (ownHateExp > 0) {
											acquire_exp = member_exp * hate
													/ ownHateExp;
										}
										AddExpPet(pet, acquire_exp);
									}
								} else if (acquisitor instanceof L1SummonInstance) {
								}
							}
						} else { // 攻撃に参加していなかった
							// パーティーメンバーのみに分配
							AddExp(ptMember, member_exp, member_lawful);
						}
					}
				}
			} else { // パーティーを組んでいない
				// EXP、ロウフルの分配
				for (i = hateList.size() - 1; i >= 0; i--) {
					acquisitor = (L1Character) acquisitorList.get(i);
					hate = hateList.get(i);
					acquire_exp = exp * hate / totalHateExp;
					if (acquisitor instanceof L1PcInstance) {
						if (totalHateLawful > 0) {
							acquire_lawful = lawful * hate / totalHateLawful;
						}
					}

					if (acquisitor instanceof L1PcInstance) {
						final L1PcInstance pc = (L1PcInstance) acquisitor;
						AddExp(pc, acquire_exp, acquire_lawful);
					} else if (acquisitor instanceof L1PetInstance) {
						final L1PetInstance pet = (L1PetInstance) acquisitor;
						AddExpPet(pet, acquire_exp);
					} else if (acquisitor instanceof L1SummonInstance) {
					}
				}
			}
		}
	}
}